package com.lmscn.lms.api.interceptor;

import com.jfinal.aop.Invocation;
import com.jfinal.aop.PrototypeInterceptor;
import com.lmscn.lms.api.controller.CourseBaseController;
import com.lmscn.lms.api.model.Student;

import java.util.List;

/**
 * Created by Czl on 2015/7/24.
 */
public class Condition extends PrototypeInterceptor {

	private static String[] order = { "create_time desc", "ckgood_num desc" };
	private String best;
	private Long studentId;

	private CourseBaseController cbc;

	/**
	 * 对Condition的属性进行赋值初始化
	 */
	private void init(Invocation ai) {
		cbc = (CourseBaseController) ai.getController();
		best = cbc.getPara("best");
		studentId = cbc.getParaToLong("studentId");
	}

	@Override
	public void doIntercept(Invocation inv) {
		init(inv);
		cbc.cond = this;
		inv.invoke();
	}

	/**
	 * 生成CourseBaseController的查询条件
	 */
	public void buildSql(StringBuilder sql, List<Object> paras) {

		// 获取学员等级
		Student student = Student.dao.findById(studentId);
		int level = student.getInt("level") == null ? 12 : student.getInt("level");

		if (best != null) {
			sql.append("from t_course_base t,t_course_lesson tc where t.id = tc.course_id ");
			sql.append(" AND t.level <= ").append(level);
			if (best.equals("0")) { // 最新
				sql.append(" order by ").append(order[0]);
			} else if (best.equals("1")) { // 好评
				sql.append(" order by ").append(order[1]);
			}
		}
		
		System.out.println(sql);
	}
}
